#include "Flash.h"
#include "Arduino.h"

Preferences preferences;

void save_pwd(int pwd_num, PWD_INFO& pwd_info){
    char* pwd_info_ptr = (char*)&pwd_info;
    
    #ifdef FLASH_DEBUG
    Serial.println("----START SAVE PWD_INFO TO NVS----");
    Serial.print("PWD_NUM:  ");
    Serial.println(pwd_num);
    #endif

    preferences.begin("pwd", false);
    String key = "pwd_" + String(pwd_num);
    preferences.putBytes(key.c_str(), pwd_info_ptr, PWD_INFO_LEN);
    preferences.end();

    #ifdef FLASH_DEBUG
    Serial.println("-------Finished SAVE PWD_INFO--------");
    #endif
}

void load_pwd(int pwd_num, PWD_INFO& pwd_info){
    pwd_info.num = pwd_num;
    char* pwd_info_ptr = (char*)&pwd_info;

    #ifdef FLASH_DEBUG
    Serial.println("---START LOAD PWD_INFO FROM NVS---");
    Serial.print("PWD_NUM:  ");
    Serial.println(pwd_num);
    #endif

    preferences.begin("pwd", true);
    String key = "pwd_" + String(pwd_num);
    size_t len = preferences.getBytes(key.c_str(), pwd_info_ptr, PWD_INFO_LEN);
    preferences.end();

    #ifdef FLASH_DEBUG
    Serial.println("-------Finished LOAD PWD_INFO--------");
    #endif
}

void load_sys(SYS_INFO& sys_info){
    char* sys_info_ptr = (char*)&sys_info;

    #ifdef FLASH_DEBUG
    Serial.println("---START LOAD SYS_INFO FROM NVS---");
    #endif

    preferences.begin("sys", true);
    size_t len = preferences.getBytes("sys_info", sys_info_ptr, SYS_INFO_LEN);
    preferences.end();

    #ifdef FLASH_DEBUG
    Serial.println("-------Finished LOAD SYS_INFO--------");
    #endif
}

void save_sys(SYS_INFO& sys_info){
    char* sys_info_ptr = (char*)&sys_info;
    
    #ifdef FLASH_DEBUG
    Serial.println("----START SAVE SYS_INFO TO NVS----");
    #endif

    preferences.begin("sys", false);
    preferences.putBytes("sys_info", sys_info_ptr, SYS_INFO_LEN);
    preferences.end();

    #ifdef FLASH_DEBUG
    Serial.println("-------Finished SAVE SYS_INFO--------");
    #endif
}

void nvs_init(SYS_INFO& sys_info,PWD_INFO& pwd_info){
    #ifdef FLASH_DEBUG
    Serial.println("-----LOAD SYS_INFO FROM NVS-----");
    #endif
    
    load_sys(sys_info);
    
    // 检查系统信息是否已初始化
    if(sys_info.sys_state == 252){
        #ifdef FLASH_DEBUG
        Serial.println();
        Serial.println("--!--NO SYS_INFO  IN  NVS--!--");
        #endif
        
        SYS_INFO sys_info_default = SYS_INFO_DEFAULT;
        PWD_INFO pwd_info_default = PWD_INFO_DEFAULT;
        
        save_sys(sys_info_default);
        save_pwd(0, pwd_info_default);
        load_sys(sys_info);
    }
    
    #ifdef FLASH_DEBUG
    Serial.print("sys_info.sys_state====");
    Serial.println(sys_info.sys_state);
    #endif
    
    load_pwd(0, pwd_info);
}